<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElDivider, ElMessage } from 'element-plus'
import {
  getUserListApi,
  saveTableApi,
  updateTableApi,
  deleteUserApi,
  assignRoleApi
} from '@/api/user'
import type { DepartmentUserItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import Allocation from './components/Allocation.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getUserListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.records || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteUserApi(unref(userCode))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'username',
    label: t('userDemo.username')
  },
  {
    field: 'gender',
    label: '性别',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '男',
            value: 0
          },
          {
            label: '女',
            value: 1
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.gender === 0 ? '男' : data.row.gender === 1 ? '女' : ''}</>
        }
      }
    }
  },
  // {
  //   field: 'reportTypeId',
  //   label: '举报类型',
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: []
  //     },
  //     optionApi: async () => {
  //       const res = await getDictApi('report_type')
  //       const list: SelectOption[] = []
  //       if (res.data.list) {
  //         res.data.list.map((item) => {
  //           list.push({
  //             label: item.name,
  //             value: item.code
  //           })
  //         })
  //       }
  //       return list
  //     }
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'cardId',
  //   label: '身份证号',
  //   component: 'Input',
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  {
    field: 'phone',
    label: '手机号码',
    component: 'Input',
    search: {
      hidden: true
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    form: {
      value: '',
      component: 'InputPassword',
      componentProps: {
        strength: true,
        placeholder: t('login.passwordPlaceholder')
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'mail',
    label: t('userDemo.email'),
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'roleNames',
    label: '角色',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const roleNames: string = data.row.roleNames.join(',')
          return roleNames
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const roleNames: string = data.roleNames.length ? data.roleNames.join(',') : ''
          return <>{roleNames}</>
        }
      }
    }
  },
  {
    field: 'roleIds',
    label: t('userDemo.role'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    form: {
      component: 'Input',
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 360,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="warning" onClick={() => allocationAction(row)}>
                {t('exampleDemo.allocation')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])
const userCode = ref('')

const delData = async (row?: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
  userCode.value = row.userId
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DepartmentUserItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const allocationVisible = ref(false)
const allocationLoading = ref(false)

const allocationAction = (row: any) => {
  currentRow.value = {
    userId: row.userId,
    roleIds: row.roleIds
  }
  allocationVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      if (formData.userId) {
        await updateTableApi(formData)
      } else {
        await saveTableApi(formData)
      }
    } catch (error) {
      console.log(error)
      ElMessage.success('保存接口异常')
    } finally {
      currentPage.value = 1
      saveLoading.value = false
      dialogVisible.value = false
      ElMessage.success('保存成功')
      getList()
    }
  }
}

const allocationSubmit = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    allocationLoading.value = true
    try {
      await assignRoleApi(formData)
    } catch (error) {
      console.log(error)
      ElMessage.success('分配接口异常')
    } finally {
      currentPage.value = 1
      allocationLoading.value = false
      allocationVisible.value = false
      ElMessage.success('分配成功')
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData()">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail v-else :detail-schema="allSchemas.detailSchema" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog title="分配角色" v-model="allocationVisible" maxHeight="200px" width="500px">
    <Allocation ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="warning" :loading="allocationLoading" @click="allocationSubmit">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="allocationVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
